package com.xjgc.common.utils;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.apache.commons.lang3.ClassUtils;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 数字类型或日期转成字符串类型
 * Created by ThinkPad on 2019/12/9.
 */
public class ObConvterStringSerializer extends JsonSerializer<Object> {

    private static  final SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    //private static  final DecimalFormat df=new DecimalFormat("#.00");

    @Override
    public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        if(value!=null) {
            if (value instanceof Date){
                gen.writeString(sdf.format(value));
            }else {
                if (ClassUtils.isPrimitiveWrapper(value.getClass())){//判断是否封装类型 如Double
                    gen.writeString(value.toString());
                }else {
                    //基本类型 如int
                    gen.writeString(String.valueOf(value));
                }
            }
        }else {//这个分支不要忘记了，否则将不输出这个属性的值
            gen.writeString("");
        }
    }

}
